/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.ncsu.gps.nmea;

import edu.ncsu.util.TimeConstants;
import org.sunspotworld.*;

/**
 *
 * @author me
 */
public class NMEAString {
    private String nmea = null;

    public boolean isValid() {
        return nmea != null;
    }

    public String getNMEAString() {
        return nmea;
    }

    public NMEAString(String input) {
        if (checkChecksum(input))  {
            nmea = input;
        }
    }

    public NMEAString() {
        
    }

    public static String NMEAInitializationString(double lastLat, double lastLon, double lastAlt) {
        if (lastLat == Double.MAX_VALUE) {
            return null;
        }
        System.out.println("Setting up GPS to last known position: Lat-"+lastLat+", Lon-"+lastLon+", Alt-"+lastAlt);
        return checksumAndFormat("PSRF104,"+lastLat+","+lastLon+","+lastAlt+",96000,"+timeOfWeek()+","+weekNum()+",12,3");

    }

    private static String checksumAndFormat(String input) {
        byte checksum = (byte)input.charAt(0);
        for (int i=1; i<input.length(); i++) {
            checksum ^= input.charAt(i);
        }
        return "$" + input + "*" + (checksum>0xF ? "" : "0") + Integer.toHexString(checksum) + "\r\n";
    }

    private static long weekNum() {
        return System.currentTimeMillis()/TimeConstants.WEEKS;
    }

    private static long timeOfWeek() {
        return System.currentTimeMillis()%TimeConstants.WEEKS;
    }

    private boolean checkChecksum(String input) {
        try {
            String check = input.substring(input.indexOf("*")+1,input.indexOf("*")+3);
            input = input.substring(input.indexOf("$")+1, input.indexOf("*"));
            byte checksum = (byte)input.charAt(0);
            for (int i=1; i<input.length(); i++) {
                checksum ^= (byte)input.charAt(i);
            }
            String sum = ((checksum>0xF ? "" : "0") + Integer.toHexString(checksum)).toUpperCase();
            return check.equals(sum);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    
}
